<template>
    <div class="photoWall">
        <el-button @click="uploadImage" class="mb10px">上传照片</el-button>
        <el-upload
            v-model:file-list="gainImage"
            action="http://127.0.0.1:3000/uloadone"
            list-type="picture-card"
            :on-preview="handlePictureCardPreview"
            :on-remove="handleRemove"
            :on-success="handleSuccess"
        >
            <el-icon><Plus /></el-icon>
        </el-upload>
        <el-dialog v-model="dialogVisible" class="dialog" >
            <img w-full :src="dialogImageUrl" alt="Preview Image" />
        </el-dialog>
    </div>
</template>

<script setup>
import { onMounted, ref, watch } from 'vue'
import { getAllPhoto, addPhoto, delPhoto } from '@/api/photoWall.js'
import { ElMessage } from 'element-plus'
const dialogImageUrl = ref('')
const dialogVisible = ref(false)
const handleRemove = async(uploadFile, uploadFiles) => {
  const res = await delPhoto({id: uploadFile.id})
    if(res.data.success){
        ElMessage.success('删除成功')
        getImage()
    }
}
//点击文件列表中已上传的文件时的钩子
const handlePictureCardPreview = async(uploadFile) => {
  dialogImageUrl.value = uploadFile.url
  dialogVisible.value = true
}
//监听到服务端返回的图片地址
const handleSuccess = (res)=>{
    console.log(res)
    
    path.value =  res.info.url
}

//拿到存储照片地址
const image = ref([])
const gainImage = ref([])
watch(()=>image.value, (nav)=>{
    gainImage.value = nav
},{deep:true})
// 获取所有照片
const getImage = ()=>{
    getAllPhoto().then(res=>{
        image.value =res.data.data.map(item=>({
            id: item.id,
            url: "http://127.0.0.1:3000" + item.photoPath
        }))
    })
}
getImage()



//添加照片
const path = ref('')
const uploadImage = async()=>{
    if(!path.value) return ElMessage.error('请上传照片')
    const res = await addPhoto({photoPath: path.value})
    gainImage.value.push(path.value)
    if(res.data.success){
        ElMessage.success('上传成功')
        getImage()
    }
}
</script>
<style scoped lang="less">
.photoWall{
    margin:0 10px;
}

</style>